package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableUserMember;

public class TagUserMember {
    public long uid;
    public int super_member_expired_time;
    public int update_time;

    public TagUserMember() {}

    public TagUserMember(long uid, int super_member_expired_time, int update_time) {
        this.uid = uid;
        this.super_member_expired_time = super_member_expired_time;
        this.update_time = update_time;
    }

    public static TagUserMember init(long uid) {
        return new TagUserMember(uid, 0, 0);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserMember.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserMember>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserMember.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUserMember>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableUserMember> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagUserMember-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableUserMember>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableUserMember> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableUserMember>, String>() {
                                    ValueState<TagUserMember> tagUserMemberVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        tagUserMemberVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagUserMember>(
                                                                        "tagUserMemberVState",
                                                                        TagUserMember.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserMember> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        int end_time = value.f1.getEnd_time();
                                        int update_time = value.f1.getUpdated_at();

                                        TagUserMember tmpState = tagUserMemberVState.value();
                                        TagUserMember curState =
                                                tmpState == null
                                                        ? TagUserMember.init(uid)
                                                        : tmpState;

                                        // 取end_time where max(update_time)
                                        if (update_time > curState.getUpdate_time()) {
                                            if (end_time
                                                    != curState.getSuper_member_expired_time()) {
                                                JSONObject jsonObject = new JSONObject();
                                                jsonObject.put("uid", uid);
                                                jsonObject.put(
                                                        "super_member_expired_time", end_time);
                                                out.collect(jsonObject.toString());

                                                curState.super_member_expired_time = end_time;
                                                curState.update_time = update_time;
                                                tagUserMemberVState.update(curState);
                                            }
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public int getSuper_member_expired_time() {
        return super_member_expired_time;
    }

    public int getUpdate_time() {
        return update_time;
    }
}
